// mixins/dictMixin.js
import { getDictList } from '@/api/common'

export default {
  data() {
    return {
      dictMap: {}
    }
  },
  methods: {
    // 单个 categoryId
    async loadDict(categoryId) {
      const cacheKey = `dict_${categoryId}`
      let dictList = []

      const cache = localStorage.getItem(cacheKey)
      if (cache) {
        try { dictList = JSON.parse(cache) }
        catch (e) { console.warn(`${cacheKey} parse error`, e) }
      }

      if (!dictList || dictList.length === 0) {
        const res = await getDictList(categoryId)
        console.log(res);

        if (res) {
          dictList = res
          localStorage.setItem(cacheKey, JSON.stringify(dictList))
        }
      }

      this.$set(this.dictMap, categoryId, dictList)
      return dictList
    },

    // 批量加载 categoryId 数组
    async loadDicts(categoryIds) {
      const promises = categoryIds.map(id => this.loadDict(id))
      await Promise.all(promises)
    },

    getDictByCategory(categoryId) {
      return this.dictMap[categoryId] || []
    },

    getDictName(categoryId, value) {
      const arr = this.dictMap[categoryId] || []
      const item = arr.find(i => i.value == value)
      return item ? item.name : ''
    }
  }
}
